from PySide6.QtWidgets import (QApplication, QMainWindow, QSplitter, QTreeView, QLineEdit, QVBoxLayout, QWidget, QLabel, QComboBox,QFormLayout,QFrame,QHBoxLayout)
from PySide6.QtCore import Qt, QStringListModel
from PySide6.QtGui import QStandardItemModel, QStandardItem
from qfluentwidgets import LineEdit,TreeView,PushButton,PrimaryPushButton,MessageBox,ComboBox

import sqlite3

def query_materials(filter_name=None, filter_category=None):
    conn = sqlite3.connect('hardware_materials.db')
    cursor = conn.cursor()

    # 构建SQL查询语句
    query = '''
    SELECT m.id, m.name, m.specification, m.theoretical_weight, c.name AS category
    FROM materials m
    LEFT JOIN categories c ON m.category_id = c.id
    '''
    conditions = []
    params = []

    if filter_name:
        conditions.append("m.name LIKE ?")
        params.append('%' + filter_name + '%')
    if filter_category and filter_category != '所有分类':
        conditions.append("c.name = ?")
        params.append(filter_category)

    if conditions:
        query += " WHERE " + " AND ".join(conditions)

    cursor.execute(query, params)

    # 获取所有结果
    materials = cursor.fetchall()

    # 关闭连接
    conn.close()

    return materials

class MaterialInfoApp(QFrame):
    def __init__(self,text: str, parent=None):
        super().__init__(parent=parent)
        self.setObjectName(text.replace(' ', '-'))

        main_layout = QHBoxLayout()

        # 创建分割器
        splitter = QSplitter(Qt.Horizontal)

        # 左侧：树形视图、搜索框、分类选择框和分类管理按钮
        left_widget = QWidget()
        left_layout = QVBoxLayout(left_widget)
        self.search_box = LineEdit(self)
        self.search_box.setPlaceholderText("搜索材料...")
        self.category_combo = ComboBox(self)
        self.category_combo.addItem("所有分类")
        self.load_categories()  # 加载分类到组合框
        self.tree_view = TreeView(self)
        self.model = QStandardItemModel()
        self.tree_view.setModel(self.model)
        # 为 TreeView 添加边框，同时保持原有样式
        self.update_tree_view_border()
        left_layout.addWidget(self.search_box)
        left_layout.addWidget(self.category_combo)
        left_layout.addWidget(self.tree_view)


        # 右侧：材料信息显示
        right_widget = QWidget()
        right_layout = QFormLayout(right_widget)
        self.material_name = LineEdit(self)
        self.material_specification = LineEdit(self)
        self.material_theoretical_weight = LineEdit(self)
        self.material_category = LineEdit(self)
        self.material_name.setReadOnly(True)
        self.material_specification.setReadOnly(True)
        self.material_theoretical_weight.setReadOnly(True)
        self.material_category.setReadOnly(True)
        right_layout.addRow(QLabel("分类:"), self.material_category)
        right_layout.addRow(QLabel("名称:"), self.material_name)
        right_layout.addRow(QLabel("规格:"), self.material_specification)
        right_layout.addRow(QLabel("理论重量:"), self.material_theoretical_weight)
        

        # 将左右两侧添加到分割器
        splitter.addWidget(left_widget)
        splitter.addWidget(right_widget)

        # 设置主窗口的中心部件为分割器
        # self.setCentralWidget(splitter)

        main_layout.addWidget(splitter)
        self.setLayout(main_layout)
        

        # 初始化数据
        self.load_materials()

        # 连接信号与槽
        self.search_box.textChanged.connect(self.filter_materials)
        self.category_combo.currentIndexChanged.connect(self.filter_materials)
        self.tree_view.clicked.connect(self.show_material_info)


    def load_categories(self):
        # 从数据库加载所有分类，并填充到组合框
        categories = query_materials()
        unique_categories = sorted(set(category[4] for category in categories if category[4]))
        self.category_combo.addItems(unique_categories)

    def update_tree_view_border(self):
        # 获取当前样式表
        current_style = self.tree_view.styleSheet()  
        
        # 定义新的边框样式
        new_style = """
            QTreeView {
                border: 1px solid #EAEAEA; /* 深色模式下的边框颜色 */
                border-radius: 2px;
            }
        """
        
        # 合并样式
        combined_style = current_style + new_style if current_style else new_style
        self.tree_view.setStyleSheet(combined_style)

    def load_materials(self):
        # 从数据库加载所有材料，并填充到模型
        materials = query_materials()
        self.update_tree_view(materials)

    def update_tree_view(self, materials):
        # 清空现有模型
        self.model.clear()

        # 设置表头
        self.model.setHorizontalHeaderLabels(["名称", "规格", "理论重量 (kg/m)"])

        for material in materials:
            # 创建每一行的项
            name_item = QStandardItem(material[1])
            specification_item = QStandardItem(material[2])
            weight_item = QStandardItem(f"{material[3]:.3f}")

            # 将所有项添加到一行中
            row = [name_item, specification_item, weight_item]

            # 将完整材料信息存储在第一列的用户数据中
            name_item.setData(material, Qt.UserRole)

            # 将这一行添加到模型中
            self.model.appendRow(row)

        # 调整列宽以适应内容
        self.tree_view.resizeColumnToContents(0)
        self.tree_view.resizeColumnToContents(1)
        self.tree_view.resizeColumnToContents(2)
        # self.tree_view.resizeColumnToContents(3)

    def filter_materials(self):
        # 根据搜索框内容和分类选择过滤材料
        filter_name = self.search_box.text().strip()
        filter_category = self.category_combo.currentText()
        materials = query_materials(filter_name=filter_name, filter_category=filter_category)
        self.update_tree_view(materials)

    def show_material_info(self, index):
        # 确保索引是有效的
        if not index.isValid():
            return

        # 获取当前行的第一列索引
        first_column_index = self.model.index(index.row(), 0)
        
        # 从第一列的索引中获取用户数据
        material = first_column_index.data(Qt.UserRole)

        if material:
            self.material_name.setText(material[1])
            self.material_specification.setText(material[2])
            self.material_theoretical_weight.setText(f"{material[3]:.3f}")
            self.material_category.setText(material[4])
